from django.db import connection

from app.decorator import jwt_auth
from app.service import order
from libs import time_helper
from libs.common import success, error
from libs.db import DB
from libs.form import RawJsonForm
from app.service.goods import query_goods_in_ids

@jwt_auth
def sale_orders(request, auth):
    cashier_id = auth.get('cashier_id')
    form = RawJsonForm(request.body)
    p = form.get_page()
    total = 0
    order_arr = []
    try:
        with connection.cursor() as cursor:
            wheres = {
                'cashier_id': cashier_id,
                'status!=-100': None,
                'deleted': 0,
            }
            keywords = form.get('keywords')
            if keywords != '':
                wheres.update({'order_sn': keywords})
            time_start = form.get('start')
            if time_start != '':
                ts = time_helper.time_str_to_ts(time_start)
                if ts > 0:
                    start_filter = 'created>={}'.format(ts)
                    wheres.update({start_filter: None})
            time_end = form.get('end')
            if time_end != '':
                ts = time_helper.time_str_to_ts(time_end)
                if ts > 0:
                    ts = ts + 86400
                    end_filter = 'created<{}'.format(ts)
                    wheres.update({end_filter: None})
            db = DB('cs_orders', conn=cursor)
            total = db.count(wheres)
            if total > 0:
                fields = ['id', 'shop_id', 'cashier_id', 'order_sn', 'pay_method',
                          'member_id', 'account', 'goods_num', 'return_num', 'return_order_sn',
                          'total_price', 'remark', 'assoc_order_id', 'status', 'trade_state_desc', 'created']
                order_arr = db.page(p).order_by('id desc').find(fields, wheres)
    except Exception as e:
        print(e.args)
    return success(order_arr, total=total, page=p.page, size=p.size)


@jwt_auth
def sale_order_detail(request, auth):
    form = RawJsonForm(request.body)
    order_id = form.get_int('id')
    shop_id = auth.get('shop_id')
    order_details = []
    pay_logs = []
    msg = ''
    try:
        with connection.cursor() as cursor:
            wheres = {
                'id': order_id,
                'shop_id': shop_id,
            }
            db = DB('cs_orders', conn=cursor)
            fields = ['id', 'shop_id', 'cashier_id', 'order_sn', 'pay_method',
                      'member_id', 'account', 'goods_num', 'return_num', 'return_order_sn',
                      'total_price', 'cart_total_price', 'remark', 'assoc_order_id', 'status', 'created','deal_type','meal_number','is_quick']
            order_row = db.order_by('id desc').one(fields, wheres)
            wheres = {
                'order_id': order_id
            }
            fields = ['id', 'goods_id', 'goods_name', 'barcode', 'amount',
                      'selling_price', 'spec_typ', 'is_input_price', 'is_discount', 'subtotal',
                      'is_half', 'half_num', 'return_num', 'return_order_id', 'status', 'created','drink_type','drink_flavor']
            db = DB('cs_order_details', conn=cursor)
            order_details = db.order_by('id desc').find(fields, wheres)
            total = len(order_details)
            if total > 0:
                goods_id_arr = []
                for g_info in order_details:
                    cart_goods_id = g_info.get('goods_id')
                    if cart_goods_id > 0:
                        goods_id_arr.append(str(cart_goods_id))
                goods_dict = query_goods_in_ids(goods_id_arr)
                for g_info1 in order_details:
                        if g_info1['goods_id'] == 0:
                            g_info1['goods_type'] = 0
                            g_info1['menu_desc'] = ""
                        else:
                            cart_gooditem = goods_dict.get(g_info1['goods_id'], None)
                            g_info1['goods_type'] = cart_gooditem.is_fast_food
                            g_info1['menu_desc'] = cart_gooditem.menu_desc
            db = DB('cs_order_pay_logs', conn=cursor)
            fields = ['id', 'pay_method_typ', 'pay_method', 'pay_typ_id',
                      'pay_amount', 'confirmed', 'tp_order_sn', 'return_amount',
                      'return_status', 'created']
            pay_logs = db.find(fields, wheres)
    except Exception as e:
        print(e.args)
        msg = '获取订单异常'
    resp_data = {
        'order': order_row,
        'order_details': order_details,
        'pay_logs': pay_logs,
        'total': total,
    }
    if msg != '':
        resp_data.update({'msg': msg})
    return success(None, **resp_data)


@jwt_auth
def mark_pay_err_order(request, auth):
    try:
        form = RawJsonForm(request.body)
        order_id = form.get('order_id', 0)
        if order_id == 0:
            return error('无效的订单ID')
        shop_id = auth.get('shop_id')
        with connection.cursor() as cursor:
            db_order, err = order.get_order_by_id(cursor, order_id, ['id', 'shop_id', 'status'])
            if err is not None:
                return error(err)
            if shop_id != db_order.get('shop_id'):
                return error('权限不足')
            if db_order.get('status') != -3:
                return error('非支付失败订单，无法作废')
            affected, _ = order.update_order_del_ts(order_id, cursor)
            if affected == 0:
                return error('更新订单状态失败')
    except Exception as e:
        err = '更新订单状态异常'
        print(err, e)
        return error(err)
    return success()
